package com.bnz.service.impl;

import com.alibaba.fastjson.JSON;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Student> findAll() {
        //从redis中查询
        String studentsJSON = stringRedisTemplate.opsForValue().get("students");
        //将拿到的json数据转为对象拿到脆响数组
        List<Student> students = JSON.parseArray(studentsJSON, Student.class);
       //判断是否youshujv
        if (students==null || students.size()==0){
            //没有则从数据库拿
            students = studentMapper.selectAll();
            stringRedisTemplate.opsForValue().set("students",JSON.toJSONString(students));
        }

        return students;
    }

    //怎加 ---- 缓存同步问题
    @Override
    public void add(Student student) {
        //先删除redis库
        stringRedisTemplate.delete("students");
        //在添加数据
        studentMapper.insert(student);
    }

    @Override
    public void update(Student student) {
        //先删除redis库
        stringRedisTemplate.delete("students");
        studentMapper.updateByPrimaryKey(student);
    }

    @Override
    public void delete(Integer sid) {
        stringRedisTemplate.delete("students");
        studentMapper.deleteByPrimaryKey(sid);
    }

}
